import React, { ComponentClass, FC, FunctionComponent, ReactNode, useCallback, useMemo } from 'react'
import { HashRouter, Route, Switch } from 'react-router-dom'
import loadable from '@routes/loadable'
import { PrivateRouteProps } from './PrivateRoute'

interface RouteType {
  path: string
  exact?: boolean
  title?: string
  component: (ComponentClass<unknown> & LoadableExport.LoadableComponent) | (FunctionComponent<unknown> & LoadableExport.LoadableComponent)
  auth?: FC<PrivateRouteProps>
  childRoute?: RouteType[]
}

export const routes: RouteType[] = [
  {
    path: '/',
    exact: true,
    component: loadable(() => import(
      /* webpackPrefetch: true */
      /* webpackChunkName:"home" */
      '@pages/home'
    ))
  }
]
const Routes: FC = () => {
  const combineRoute = useCallback((routesArr: RouteType[], arr: ReactNode[]) => {
    routesArr.forEach(Route_ => {
      if (Route_?.childRoute?.length) {
        combineRoute(Route_.childRoute, arr)
      }
      if (Route_.auth) {
        arr.push(<Route_.auth key={Route_.path + 'route'} {...Route_} />)
      } else {
        arr.push(<Route key={Route_.path + 'route'} {...Route_} />)
      }
    })
    return arr
  }, [])

  const routeData = useMemo(() => {
    const route: ReactNode[] = []
    return combineRoute(routes, route)
  }, [routes])

  return (
    <HashRouter>
      <Switch>
        {routeData.map(item => item)}
      </Switch>
    </HashRouter>
  )
}

export default Routes
